<?php
namespace app\controller;

use app\model\RoomsReport as RoomsReportModel;
use app\Request;
use app\service\GameTools;
use app\validate\RoomsValid;

use app\model\Rooms as RoomsModel;
use app\model\RoomsPlayer as RoomsPlayerModel;

use app\service\Geteway as GetewayService;

use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
/**
 * @author yanxusheng <[<ausheng@foxmail.com>]>
 * @datetime 2023/8/4 14:02
 * @content 赛事房间管理器
 */
class Rooms extends Communal
{
    /**
     * @param Request $request
     * @param RoomsValid $valid
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function list(Request $request, RoomsValid $valid)
    {
        if(!$valid->scene('list-all')->check($request->post())){
            $this->error($valid->getError());
        }
        // 获取变量
        $params = $request->post(['room_title', 'room_region']);

        $result = RoomsModel::GetList($params);

        if ($result->isEmpty()) {
            $resp = ['list' => [], 'count' => count($result)];
        } else {
            $resp = ['list' => $result->toArray(), 'count' => count($result)];
        }

        $this->success($resp);
    }



    /**
     * @param Request $request
     * @param RoomsValid $valid
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function person(Request $request, RoomsValid $valid)
    {
        if(!$valid->scene('list-all')->check($request->post())){
            $this->error($valid->getError());
        }
        $result = RoomsModel::GetInfoByKeyword('create_id', $request->usersId, '1,2,3,4');
        if ($result->isEmpty()) {
            $result = RoomsPlayerModel::GetPersonInfo('bakal_rooms_player.player_id', $request->usersId);
            if ($result->isEmpty()) {
                $this->error();
            }
        }

        $this->success($result);
    }



    /**
     * @param Request $request
     * @param RoomsValid $valid
     */
    public function create(Request $request, RoomsValid $valid) {
        if(!$valid->scene('create')->check($request->post())){
            $this->error($valid->getError());
        }
        // 获取变量
        $params = $request->post(['room_title', 'room_region', 'room_type', 'is_password', 'room_password', 'start_time', 'room_reward', 'room_content']);
        // 首先判断是否存在多个房间 （房主）
        $resp_model = RoomsModel::GetInfoByKeyword('create_id', $request->usersId, '1,2,3');
        if (!$resp_model->isEmpty()) {
            $this->error("您已经创建了另外一个房间，该房间状态并未结束，无法再次发布赛事");
        }
        // 首先判断是否存在多个房间 （队员）
        $resp_list = RoomsPlayerModel::HasJoinRoomByPlayerId($request->usersId);
        if (!$resp_list->isEmpty()) {
            $this->error("您已经加入了另外一个房间，该房间赛事未结束");
        }

        // 拼接数组、保存
        $params['room_player_num'] = 1;
        $params['room_code'] = guid_code();
        $params['create_id'] = $request->usersId;
        $params['create_time'] = time();

        $last_id = RoomsModel::SaveInsertGetId($params);
        if (!$last_id) {
            $this->error('发布赛事失败，请联系管理员【RoomsModel::SaveInsertGetId】');
        } else {
            if (!RoomsPlayerModel::SaveInsertInfo([
                'room_code'     => $params['room_code'],
                'room_id'       => $last_id,
                'player_code'   => $request->usersCode,
                'player_id'     => $request->usersId,
                'master'        => 1,
                'create_time'   => time(),
            ])) {
                // 保存房主信息失败，那就撤销发布
                RoomsModel::SaveEditInfo($last_id, ['room_status' => '0']);
                $this->error('发布赛事失败，请联系管理员【RoomsModel::SaveEditInfo】');
            }
        }

        $this->success(['room_code' => $params['room_code']]);
    }



    /**
     * @param Request $request
     * @param RoomsValid $valid
     */
    public function close(Request $request, RoomsValid $valid) {
        if (!$valid->scene('close')->check($request->post())) {
            $this->error($valid->getError());
        }
        $room_code = $request->post('room_code');

        $resp_room = RoomsModel::GetInfoByKeyword('room_code', $room_code);
        if ($resp_room->isEmpty() || ($resp_room->room_status != '1' && $resp_room->room_status != '3')) {
            $this->error("房间赛事已经开始，当前状态无法关闭");
        }
        // 核验权限
        if ($resp_room->create_id != $request->usersId) {
            $this->error("权限不足，无法关闭赛事");
        }

        // 都没有问题，关闭赛事
        if (!RoomsModel::SaveEditByKeyword('room_code', $room_code, ['room_status' => '0'])) {
            $this->error("系统错误，请联系管理员【RoomsModel::SaveEditByKeyword】");
        } else {
            // 这里改一下 省的查了
            $resp_room->room_status = 0;
        }
        // 修改房间内所有玩家的状态
        if (!RoomsPlayerModel::SaveEditByKeyword('room_code', $room_code, ['status' => '0'])) {
            $this->error("系统错误，请联系管理员【RoomsPlayerModel::SaveEditByKeyword】");
        }

        // 主动关闭socket
        $service = new GetewayService();
        // 推送关闭房间的信息
        if (!$service->SendGroupMsg($room_code, $resp_room->toArray(), 'room_info')) {
            $this->error('系统错误，请联系管理员【$service->SendGroupMsg】');
        }
        // 关闭链接
        if (!$service->CloseRooms($room_code)) {
            $this->error('系统错误，请联系管理员【$service->CloseRooms】');
        }

        $this->success();
    }


    /**
     * @param Request $request
     * @param RoomsValid $valid
     */
    public function start(Request $request, RoomsValid $valid) {
        if (!$valid->scene('close')->check($request->post())) {
            $this->error($valid->getError());
        }
        $room_code = $request->post('room_code');

        $resp_room = RoomsModel::GetInfoByKeyword('room_code', $room_code);
        if ($resp_room->isEmpty() || ($resp_room->room_status != '1')) {
            $this->error("房间赛事已经开始，不需要再次开启");
        }
        // 核验权限
        if ($resp_room->create_id != $request->usersId) {

            $this->error("权限不足，无法开启赛事");
        }

        // 判断人数够不够
        $resp_r_player_list = RoomsPlayerModel::GetPlayerListByKeyword('room_code', $room_code, '2');
        if ($resp_r_player_list->count() < 12) {
            $this->error("还有成员没有准备好呢，再等等");
        }

        // 人数够了 那就修改房间状态
        if (!RoomsModel::SaveEditByKeyword('room_code', $room_code, ['room_status' => '2', 'game_start_time' => time()])) {
            $this->error('系统错误，请联系管理员【RoomsModel::SaveEditByKeyword】');
        } else {
            // 这样改一下省得再查一次了
            $resp_room->room_status = 2;
        }
        // 修改赛事选手状态
        if (!RoomsPlayerModel::SaveEditByKeywordAndStatus('room_code', $room_code, '2', ['status' => '3'])) {
            $this->error('系统错误，请联系管理员【RoomsPlayerModel::SaveEditByKeywordAndStatus】');
        }

        $service = new GetewayService();
        // 发送开始比赛信息 - 其实就是房间信息
        if (!$service->SendGroupMsg($room_code, $resp_room->toArray(), 'room_info')) {
            $this->error($service->error_msg.'【$service->SendGroupMsg】');
        }

        // 发送玩家列表
        $player_list = RoomsPlayerModel::GetPlayerListByKeyword('room_code', $room_code);
        if (!$service->SendGroupMsg($room_code, $player_list->toArray(), 'player_list')) {
            $this->error($service->error_msg.'【$service->SendGroupMsg】');
        }

        // 发送玩家信息
        $player_info = RoomsPlayerModel::GetPersonInfo('bakal_rooms_player.player_code', $request->usersCode);
        if (!$service->SendUidMsg($request->usersCode, $player_info->toArray(), 'player_info')) {
            $this->error($service->error_msg.'【$service->SendUidMsg】');
        }

        $this->success($player_info);
    }


    /**
     * @param Request $request
     * @param RoomsValid $valid
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function response(Request $request, RoomsValid $valid) {
        if (!$valid->scene('close')->check($request->post())) {
            $this->error($valid->getError());
        }
        $room_code = $request->post('room_code');

        $resp_room = RoomsModel::GetInfoByKeyword('room_code', $room_code);
        if ($resp_room->isEmpty() || ($resp_room->room_status != '3')) {
            $this->error("赛事还没有结束，暂时无法查询有效信息");
        } else {
            $resp_room->game_start_time = date('m-d, H:i', $resp_room->game_start_time);
            $resp_room->end_time = date('m-d, H:i', $resp_room->end_time);
        }

        $response = [
            'room_info' => $resp_room,
            'report_list' => [],
            'player_list' => [],
        ];
        // 然后三个tab  获胜人员、投票流水、全体人员身份卡
        $report_list = RoomsReportModel::GetListByKeyword('room_coed', $room_code)->toArray();
        $tools = new GameTools();
        $response['report_list'] = $tools->ReportListByUnPlayer($report_list);

        // 玩家列表
        $player_list = RoomsPlayerModel::GetPlayerListByKeyword('room_code', $room_code, '1,2,3,4,0')->toArray();
        foreach ($player_list as $key => $val) {
            $player_list[$key]['task'] = json_decode($val['task']);
        }
        $response['player_list'] = $player_list;

        $this->success($response);
    }










}